在經歷了傳統 CSS 後,發現了一些 CSS 的缺點
.card {},假設是寫在純 css 檔中,使用 import 'app.css' 的方式引用,在其他 component 的 html 同樣具有 card 的class name,將會吃到這個相同的屬性,並不能針對不同 component 有獨特的 style 樣式,會污染其他 component。
使用 css 方式
//example.js
useEffect(()=>{
	document.querySelect('.customer-container').style.setProperty('--current-height',
  '200px')
},[])
<div classname="customer-container"></div>
//example.css
{
 .customer-container{
   height:var(--current-height);
  }
}
//這邊一個 height 就要埋一個變數,試想假設有 width 或其他變數,也會造成埋過多的 var 屬性
使用 style-component 寫法
<Wrapper width={width} height={height} />
</Wrapper>
const Wrapper = styled.div`
  width: ${p => p.width};
  height: ${p => p.height};
`;
// 這樣的寫法就乾淨很多,而且可以帶很多變數當成 props 到 Wrapper
CSS in JS 則不用考慮過多的命名
// 使用傳統 css
// BEM 命名, 為了區別 nav 區塊需要命名 nav__item, 命名狀態需要 --active
  <div class="nav">
    <li class="nav__item nav__item--active"><a href="#about">About</a></li>
    <li class="nav__item"><a href="#product">Product</a></li>
  </div>
//使用 emotion
<div
    css={css`
     ......
    `}
  >
    <li
      css={css`
       ....
      `}
    >
     <a href="#about">About</a>
    </li>
		<li
      css={css`
       ....
      `}
    >
     <a href="#product">Product</a>
    </li>
  </div>
//在每個 element 都有屬於自己的 css 樣式,就不用過度命名
這時候我們就需要依靠 CSS in JS 來解決這些缺點,我們下一篇將介紹 emotion css 的使用。
https://blog.logrocket.com/5-things-you-can-do-css-in-js/
https://www.joshwcomeau.com/css/styled-components/
https://dev.to/rleija_/5-reasons-to-go-with-css-in-js-for-your-next-application-43m
https://blog.logrocket.com/5-things-you-can-do-css-in-js/